package com.store.app.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.ShoppingCarAdapter;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.ShopCarBean;
import com.store.app.bean.ShoppingInfo;
import com.store.app.bean.WypGoodsBean;
import com.store.app.http.Stores;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.Utils;

import org.json.JSONObject;

import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/11/22.
 * 购物车页面
 */
public class ShoppingCarActivity extends BaseActivity implements IOnHttpListener {
    private List<ShoppingInfo> shoppingInfoList;
    private ShoppingCarAdapter shoppingCarAdapter;
    private ListView lv;
    private ImageView public_ll_return;
    private TextView tvTitle;
    private TextView allMoney;
    private TextView all_price;
    private LinearLayout lin_pay;//去结算
    private CheckBox c_check;
    private TextView tv_check;
    private NetRequest netRequest;
    private EditText etStoreName;
    private EditText compay_edit_tel;
    private EditText tv_location;

    List<ShoppingInfo> chooseList;//选中的购物车(提交订单时候提给服务器)
    List<ShoppingInfo> noChooseList;//没选中的购物车（提交订单成功之后复制给本地购物车）
    private TextView tv_rel_fee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_car);
        ExitApplication.getInstance().addActivity(this);
        shoppingInfoList = (List<ShoppingInfo>) getIntent().getSerializableExtra("listData");
        EventBus.getDefault().register(this);
        netRequest = new NetRequest(this);
        initView();
        initListeners();
        initData();
        queryPromotion();
    }

    private void initData() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if (TextUtils.isEmpty(Stores.address)) {
            Stores.address = preferences.getString("address", "");
        }
        if (TextUtils.isEmpty(Stores.area_desc)) {
            Stores.area_desc = preferences.getString("area_desc", "");
        }
        if (!TextUtils.isEmpty(Stores.contact_person)) {
            etStoreName.setText(Stores.contact_person);
        }
        tv_location.setEnabled(false);
        compay_edit_tel.setEnabled(false);
        etStoreName.setEnabled(false);
        if (!TextUtils.isEmpty(Stores.contact_tel)) {
            compay_edit_tel.setText(Stores.contact_tel);
        }
        if (!TextUtils.isEmpty(Stores.address) && !TextUtils.isEmpty(Stores.area_desc)) {
            tv_location.setText(Stores.area_desc + Stores.address);
        }
    }

    /**
     * 查询列表的促销规则
     */
    public void queryPromotion() {
        String all_supplier_id = "";
        for (int i = 0; i < shoppingInfoList.size(); i++) {
            all_supplier_id += shoppingInfoList.get(i).getSupplierId() + ",";
        }
        netRequest.requestSupplierListPromotionFind(1, all_supplier_id);
    }

    @Override
    public void finish() {
        super.finish();
        //通知我要批页面下面条目选中首页
        EventBus.getDefault().post(shoppingInfoList);
        EventBus.getDefault().post(new EventBusBean(210));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEvent(EventBusBean busBean) {
        if (busBean.type == 208) {
            shoppingInfoList.get(busBean.index).setReal_fee(busBean.data);
        }
    }

    public void onEvent(ShopCarBean event) {
        Log.v("zyl", "onEvent isCheck():" + event.isCheck());
        Log.v("zyl", "onEvent getPosition():" + event.getPosition());

        for (int i = 0; i < shoppingInfoList.size(); i++) {
            Log.v("zyl", shoppingInfoList.get(i).getSupplierName() + "   isCheck:" + shoppingInfoList.get(i).isCheck());
            for (int j = 0; j < shoppingInfoList.get(i).getBookedBeanList().size(); j++) {
                Log.v("zyl", shoppingInfoList.get(i).getBookedBeanList().get(j).getTitle() + "   isCheck:" + shoppingInfoList.get(i).getBookedBeanList().get(j).ischecek());
            }
        }
        if (event.getType() == 1) {
            if (event.isCheck()) {
                Log.v("zyl", "全都设置为ture");
                shoppingInfoList.get(event.getPosition()).setIsCheck(true);
                for (int i = 0; i < shoppingInfoList.get(event.getPosition()).getBookedBeanList().size(); i++) {
                    shoppingInfoList.get(event.getPosition()).getBookedBeanList().get(i).setIschecek(true);
                }
                shoppingCarAdapter.notifyDataSetChanged();
            }
            //说明现在标题关闭了，则要遍历关闭所有子条目
            else {
                Log.v("zyl", "全都设置为false");
                shoppingInfoList.get(event.getPosition()).setIsCheck(false);
                for (int i = 0; i < shoppingInfoList.get(event.getPosition()).getBookedBeanList().size(); i++) {
                    shoppingInfoList.get(event.getPosition()).getBookedBeanList().get(i).setIschecek(false);
                }
                shoppingCarAdapter.notifyDataSetChanged();
            }
        } else if (event.getType() == 2) {
            //变化后的状态未true，则修改对应条目的数据，再判断其他条目是否为true,如果是，则激活父窗体的true状态
            if (event.isCheck()) {
                shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).setIschecek(true);
                boolean isChoose = true;
                for (int i = 0; i < shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().size(); i++) {

                    if (i == event.getPosition()) {
                        continue;
                    }
                    if (!shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(i).ischecek()) {
                        isChoose = false;
                    }
                }
                if (isChoose) {
                    shoppingInfoList.get(event.getParentPosition()).setIsCheck(true);
                } else {
                    shoppingInfoList.get(event.getParentPosition()).setIsCheck(false);
                }
                shoppingCarAdapter.notifyDataSetChanged();
            }
            //变化后的状态未false,则修改对应的item的数据，并且关闭夫条目的ture状态
            else {
                shoppingInfoList.get(event.getParentPosition()).setIsCheck(false);
                shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).setIschecek(false);
                shoppingCarAdapter.notifyDataSetChanged();
            }
        }


        //商品数量+1

        else if (event.getType() == 3) {
            final int maxNum;//限购数量
            if (TextUtils.isEmpty(shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).getMax_buy_qty())) {
                maxNum = 0;
            } else {
                maxNum = Integer.parseInt((shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).getMax_buy_qty()));
            }
            int countCount = shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).getBuyCount();
            int i_min_count = Integer.parseInt(shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).getMin_buy_qty());//得到最小起订量
            WypGoodsBean bean = shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition());
            int sale_qty = Integer.parseInt(bean.getSpecificationsBeanList().get(bean.getChooseIndexSpeci()).getSale_qty());//得到商品库存
            //如果限购小于等于0
            if (maxNum <= 0) {
                if (countCount + i_min_count > sale_qty) {
                    ToastTools.showShort(ShoppingCarActivity.this, "库存不足！");
                    return;
                }
                shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).setBuyCount(countCount + i_min_count);
            } else {
                Log.v("zyl", "countCount：" + countCount);
                Log.v("zyl", "i_min_count：" + i_min_count);
                Log.v("zyl", "sale_qty：" + sale_qty);
                //如果购买数量大于了限购，则不允许加了
                if (countCount + i_min_count > maxNum) {
                    ToastTools.showShort(ShoppingCarActivity.this, "已达到限购数量");
                } else if (countCount + i_min_count > sale_qty) {
                    ToastTools.showShort(ShoppingCarActivity.this, "库存不足");
                    return;
                } else {
                    shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).setBuyCount(countCount + i_min_count);
                }
            }
            shoppingCarAdapter.notifyDataSetChanged();
        }
        //商品数量-1
        else if (event.getType() == 4) {
            int i_min_count = Integer.parseInt(shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).getMin_buy_qty());//得到最小起订量
            int countCount = shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).getBuyCount();
            //如果数量大于起订量则可以减小
            if (countCount > i_min_count) {
                shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().get(event.getPosition()).setBuyCount(countCount - i_min_count);

            } else if (countCount == i_min_count) {
                shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().remove(event.getPosition());
            }
            if (shoppingInfoList.get(event.getParentPosition()).getBookedBeanList().size() == 0) {
                shoppingInfoList.remove(event.getParentPosition());
            }
            shoppingCarAdapter.notifyDataSetChanged();
        } else {

        }


        for (int i = 0; i < shoppingInfoList.size(); i++) {
            Log.v("zyl", "修改后数据：" + shoppingInfoList.get(i).getSupplierName() + "   isCheck:" + shoppingInfoList.get(i).isCheck());
            for (int j = 0; j < shoppingInfoList.get(i).getBookedBeanList().size(); j++) {
                Log.v("zyl", "修改后数据：" + shoppingInfoList.get(i).getBookedBeanList().get(j).getTitle() + "   isCheck:" + shoppingInfoList.get(i).getBookedBeanList().get(j).ischecek());
            }
        }
        //刷新最后全选按钮的状态
        refreshCheckBoxState();
        refreshPrice();
    }

    //刷新最后一个checkBox的状态
    public void refreshCheckBoxState() {
        //是否所有父窗体都打勾
        boolean isAllSelect = true;
        for (int x = 0; x < shoppingInfoList.size(); x++) {
            Log.v("zyl", x + "  isCheck" + shoppingInfoList.get(x).isCheck());
            if (!shoppingInfoList.get(x).isCheck()) {
                isAllSelect = false;
            }
        }
        if (isAllSelect) {
            c_check.setChecked(true);
        } else {
            c_check.setChecked(false);
        }
    }

    //刷新价格
    public void refreshPrice() {
        String money = calAlldMoney();
        String relFee = callRelFee();
        tv_rel_fee.setText(relFee);
        allMoney.setText(money);
        all_price.setText(MoneyUtil.moneyAdd(money,relFee));
    }

    //计算合计价格，取出集合中所有选中的商品*价格
    public String calAlldMoney() {
        String allMoney = "0";
        for (int i = 0; i < shoppingInfoList.size(); i++) {
            ShoppingInfo tempShoppingInfo = shoppingInfoList.get(i);
            List<WypGoodsBean> temBookList = tempShoppingInfo.getBookedBeanList();
            for (int j = 0; j < temBookList.size(); j++) {
                WypGoodsBean temBookBean = temBookList.get(j);
                //如果是选中状态，取出价格跟数量
                if (temBookBean.ischecek()) {
                    int temCount = temBookBean.getBuyCount();
                    String tempMoney = temBookBean.getLastMoney();
                    String singMoney = MoneyUtil.moneyMul(temCount + "", tempMoney);
                    allMoney = MoneyUtil.moneyAdd(allMoney, singMoney);
                }
            }
        }
        return MoneyUtil.formatMoney(allMoney);
    }

    private String callRelFee(){
        String relMoney = "0";
        for(int i = 0;i<shoppingInfoList.size();i++){
            ShoppingInfo tempShoppingInfo = shoppingInfoList.get(i);
            List<WypGoodsBean> temBookList = tempShoppingInfo.getBookedBeanList();
            String temMoney = "0";
            for (int j = 0; j < temBookList.size(); j++) {
                WypGoodsBean temBookBean = temBookList.get(j);
                //如果是选中状态，取出价格跟数量
                if (temBookBean.ischecek()) {
                    int temCount = temBookBean.getBuyCount();
                    String tempMoney = temBookBean.getLastMoney();
                    String singMoney = MoneyUtil.moneyMul(temCount + "", tempMoney);
                    temMoney = MoneyUtil.moneyAdd(temMoney, singMoney);
                }
            }
            Log.v("zyl","供应商："+i+"   "+temMoney);
            //得到该供应商的商品总价。
            if(!MoneyUtil.moneyBigThan(temMoney,"0")){

            }else if(MoneyUtil.moneyComp(temMoney,tempShoppingInfo.getStarting_price())){

            }else {
                relMoney  =  MoneyUtil.moneyAdd(relMoney,tempShoppingInfo.getShipping_fee());
            }
        }
        Log.v("zyl","relMoney:"+relMoney);
        return MoneyUtil.formatMoney(relMoney);
    }


    public String calRelFee() {
        String relFee = "0";
        for (int i = 0; i < shoppingInfoList.size(); i++) {
            relFee = MoneyUtil.moneyAdd(relFee, shoppingInfoList.get(i).getReal_fee());
        }
        return MoneyUtil.formatMoney(relFee);
    }

    private void initView() {
        lv = (ListView) findViewById(R.id.lv);
        tv_rel_fee = (TextView) findViewById(R.id.tv_rel_fee);
        Log.v("zyl", "接收到的shoppingInfoList：" + shoppingInfoList.size());
        shoppingCarAdapter = new ShoppingCarAdapter(shoppingInfoList, this);
        lv.setAdapter(shoppingCarAdapter);
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("购物车");
        allMoney = (TextView) findViewById(R.id.allMoney);
        all_price = (TextView) findViewById(R.id.all_price);
//        refreshPrice();
        lin_pay = (LinearLayout) findViewById(R.id.btnPay);
        c_check = (CheckBox) findViewById(R.id.c_check);
        tv_check = (TextView) findViewById(R.id.tv_check);
        tv_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                c_check.setChecked(!c_check.isChecked());
                if (c_check.isChecked()) {
                    for (int i = 0; i < shoppingInfoList.size(); i++) {
                        List<WypGoodsBean> bookedBeanList = shoppingInfoList.get(i).getBookedBeanList();
                        shoppingInfoList.get(i).setIsCheck(true);
                        for (int j = 0; j < bookedBeanList.size(); j++) {
                            bookedBeanList.get(j).setIschecek(true);
                        }
                    }
                } else {
                    for (int i = 0; i < shoppingInfoList.size(); i++) {
                        List<WypGoodsBean> bookedBeanList = shoppingInfoList.get(i).getBookedBeanList();
                        shoppingInfoList.get(i).setIsCheck(false);
                        for (int j = 0; j < bookedBeanList.size(); j++) {
                            bookedBeanList.get(j).setIschecek(false);
                        }
                    }
                }
                shoppingCarAdapter.notifyDataSetChanged();
                refreshPrice();
            }
        });


//        c_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked) {
//                    for (int i = 0; i < shoppingInfoList.size(); i++) {
//                        List<BookedBean> bookedBeanList = shoppingInfoList.get(i).getBookedBeanList();
//                        shoppingInfoList.get(i).setIsCheck(true);
//                        for (int j = 0; j < bookedBeanList.size(); j++) {
//                            bookedBeanList.get(j).setIschecek(true);
//                        }
//                    }
//                } else {
//                    for (int i = 0; i < shoppingInfoList.size(); i++) {
//                        List<BookedBean> bookedBeanList = shoppingInfoList.get(i).getBookedBeanList();
//                        shoppingInfoList.get(i).setIsCheck(false);
//                        for (int j = 0; j < bookedBeanList.size(); j++) {
//                            bookedBeanList.get(j).setIschecek(false);
//                        }
//                    }
//                }
//                shoppingCarAdapter.notifyDataSetChanged();
//                refreshPrice();
//            }
//        });
        refreshCheckBoxState();
        refreshPrice();

        etStoreName = (EditText) findViewById(R.id.etStoreName);
        compay_edit_tel = (EditText) findViewById(R.id.compay_edit_tel);
        tv_location = (EditText) findViewById(R.id.tv_location);

    }


    private void initListeners() {
        lin_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (shoppingInfoList.size() == 0) {
                    ToastTools.showShort(ShoppingCarActivity.this, "购物车为空！请先添加商品。");
                    return;
                }
                boolean ifChoose = false; //是否有选中的商品
                for (int i = 0; i < shoppingInfoList.size(); i++) {
                    String name = shoppingInfoList.get(i).getSupplierName();
                    List<WypGoodsBean> tep = shoppingInfoList.get(i).getBookedBeanList();
                    for (int j = 0; j < tep.size(); j++) {
                        if (tep.get(j).ischecek()) {
                            ifChoose = true;
                        }
                    }
                }
                if (!ifChoose) {
                    ToastTools.showShort(ShoppingCarActivity.this, "未选中商品");
                    return;
                }

                if(!MoneyUtil.moneyBigThan(all_price.getText().toString().trim(),"0")){
                    ToastTools.showShort(ShoppingCarActivity.this, "应付价格不能小于0");
                    return;
                }
                //取出shoppingInfoList 中勾选的商品
//                chooseList = new ArrayList<>();
//                noChooseList = new ArrayList<>();
//                chooseList.addAll(shoppingInfoList);
//                noChooseList.addAll(shoppingInfoList);
                //用原来的集合，移除选中的，得到未选中的购物车
//                for(int i = 0;i<noChooseList.size();i++){
//                    for(int j = 0;j<noChooseList.get(i).getBookedBeanList().size();j++){
//                        if(noChooseList.get(i).getBookedBeanList().get(j).ischecek()){
//                            noChooseList.get(i).getBookedBeanList().remove(noChooseList.get(i).getBookedBeanList().get(j));
//                        }
//                    }
//                }
//                //得到选中的购物车
//                for(int i = 0;i<chooseList.size();i++){
//                    for(int j = 0;j<chooseList.get(i).getBookedBeanList().size();j++){
//                        if(!chooseList.get(i).getBookedBeanList().get(j).ischecek()){
//                            chooseList.get(i).getBookedBeanList().remove(chooseList.get(i).getBookedBeanList().get(j));
//                        }
//                    }
//                    if(chooseList.get(i).getBookedBeanList().size()==0){
//                        chooseList.remove(i);
//                    }
//                }

                //remove之前
//                for (int i = 0; i < shoppingInfoList.size(); i++) {
//                    String name = shoppingInfoList.get(i).getSupplierName();
//                    Log.v("zyl", "remove之前name:" + name);
//                    List<WypGoodsBean> tep = shoppingInfoList.get(i).getBookedBeanList();
//                    Log.v("zyl", "chooseList" + tep.size());
//                    for (int j = 0; j < tep.size(); j++) {
//                        Log.v("zyl", "tep id+guige:" + tep.get(j).getGoodsidAndstockId());
//                        Log.v("zyl", "tep name:" + tep.get(j).getTitle());
//                        Log.v("zyl", "tep count:" + tep.get(j).getBuyCount());
//                        Log.v("zyl", "tep guige:" + tep.get(j).getSpecificationsBeanList().get(tep.get(j).getChooseIndexSpeci()).getDesc1());
//                    }
//                }
                for (int i = 0; i < shoppingInfoList.size(); i++) {
                    for (int j = 0; j < shoppingInfoList.get(i).getBookedBeanList().size(); j++) {
                        if (!shoppingInfoList.get(i).getBookedBeanList().get(j).ischecek()) {
                            shoppingInfoList.get(i).getBookedBeanList().remove(shoppingInfoList.get(i).getBookedBeanList().get(j));
                        }
                    }
                    if (shoppingInfoList.get(i).getBookedBeanList().size() == 0) {
                        shoppingInfoList.remove(i);
                    }
                }
//                //remove之后
//                for (int i = 0; i < shoppingInfoList.size(); i++) {
//                    String name = shoppingInfoList.get(i).getSupplierName();
//                    Log.v("zyl", "remove之后 name:" + name);
//                    List<WypGoodsBean> tep = shoppingInfoList.get(i).getBookedBeanList();
//                    Log.v("zyl", "chooseList" + tep.size());
//                    for (int j = 0; j < tep.size(); j++) {
//                        Log.v("zyl", "tep id+guige:" + tep.get(j).getGoodsidAndstockId());
//                        Log.v("zyl", "tep name:" + tep.get(j).getTitle());
//                        Log.v("zyl", "tep count:" + tep.get(j).getBuyCount());
//                        Log.v("zyl", "tep guige:" + tep.get(j).getSpecificationsBeanList().get(tep.get(j).getChooseIndexSpeci()).getDesc1());
//                    }
//                }

//                //得到选中的购物车 temList2
//                for (int i = 0; i < noChooseList.size(); i++) {
//                    String name = noChooseList.get(i).getSupplierName();
//                    Log.v("zyl", "name:" + name);
//                    List<WypGoodsBean> tep = noChooseList.get(i).getBookedBeanList();
//                    Log.v("zyl", "noChooseList" + tep.size());
//                    for (int j = 0; j < tep.size(); j++) {
//                        Log.v("zyl", "tep id+guige:" + tep.get(j).getGoodsidAndstockId());
//                        Log.v("zyl", "tep name:" + tep.get(j).getTitle());
//                        Log.v("zyl", "tep count:" + tep.get(j).getBuyCount());
//                        Log.v("zyl", "tep guige:" + tep.get(j).getSpecificationsBeanList().get(tep.get(j).getChooseIndexSpeci()).getDesc1());
//                    }
//                }
                netRequest.requestWypOrderCreate(2, shoppingInfoList);
            }
        });
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                jsonObject = jsonObject.getJSONObject("promotion");
                for (int i = 0; i < shoppingInfoList.size(); i++) {
                    ShoppingInfo shoppingInfo = shoppingInfoList.get(i);
                    JSONObject temJsonobj = jsonObject.getJSONObject(shoppingInfo.getSupplierId());
                    shoppingInfoList.get(i).setStarting_price(temJsonobj.getString("starting_price"));
                    shoppingInfoList.get(i).setShipping_fee(temJsonobj.getString("shipping_fee"));
                    shoppingCarAdapter.notifyDataSetChanged();
                }
            } catch (Exception e) {

            }
            refreshPrice();
        } else if (requestId == 2) {

            Intent intent = new Intent(ShoppingCarActivity.this, TheSingleOrderActivity.class);
            intent.putExtra("showFragmentIndex", "1");
            startActivity(intent);
            shoppingInfoList.clear();
            finish();
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        ToastTools.showShort(ShoppingCarActivity.this, msg);
    }

}
